package top.eggcode.component.dingtalk;

import com.alibaba.fastjson.JSON;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.fastjson.FastjsonMsgConvertor;
import okhttp3.OkHttpClient;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class DingRobotClientImpl implements DingRobotClient {

    private static final Logger logger = LoggerFactory.getLogger(DingRobotClientImpl.class);

    private final String webhookUrl;

    private final String secret;

    public DingRobotClientImpl(String webhookUrl, String secret) {
        this.webhookUrl = webhookUrl;
        this.secret = secret;
    }

    @Override
    public void pushMessage(Object message) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        long time = System.currentTimeMillis();
        String sign = sign(time);

        String targetUrl = webhookUrl.concat("&timestamp=").concat(String.valueOf(time)).concat("&sign=").concat(sign);
        HTTP http = HTTP.builder()
                .addMsgConvertor(new FastjsonMsgConvertor())
                .config((OkHttpClient.Builder builder) -> {
                    // 连接超时时间
                    builder.connectTimeout(5, TimeUnit.SECONDS);
                })
                .build();
        http.async(targetUrl)
                .bodyType("application/json;charset=utf-8")
                .setBodyPara(JSON.toJSONString(message))
                .setOnResponse((HttpResult res) -> {
                    int status = res.getStatus();
                    HttpResult.Body body = res.getBody();
                    System.out.println(body.toString());
                    logger.debug("请求状态码：" + status);
                    logger.debug("返回结果：".concat(body.toString()));
                })
                .setOnException(Throwable::printStackTrace)
                .post();
    }

    private String sign(long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        String result = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return result;
    }
}
